package gen.tools.role;

import gen.tools.Widgets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class QueryEmpInEnv extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public QueryEmpInEnv() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/json");
		response.setCharacterEncoding( wid.UIcodeSet );
		
		int systemId = Integer.parseInt( request.getParameter("systemId") );
		String subsysId = request.getParameter("subsysId");
		int roleId = Integer.parseInt( request.getParameter("roleId") );
		String empId = request.getParameter("empId");
		
		
		List<String> envs = new ArrayList<String>();
		
		
		String sql = "";
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		try {
			conn = wid.getConn();
			
			//所有子系統, 環境下擁有指定角色的人
			sql = "SELECT envId FROM mpemprolesubsysenv WHERE subsysId=? AND roleId=? AND empId=? AND sysSN=?";
			
			ps = conn.prepareStatement( sql );
			int i=1;
			ps.setString(i++, subsysId);
			ps.setInt(i++, roleId);
			ps.setString(i++, empId);
			ps.setInt(i++, systemId);
			rs = ps.executeQuery();
			while ( rs.next() ) {
				envs.add( rs.getString("envId") );
			}
		} catch (Exception e) {
			wid.errLog(e);
		} finally {
			try {
				if ( rs !=null ) {rs.close();}
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}	
			} catch (Exception e) { e.printStackTrace(); };
			
		}
		
		response.getWriter().write( new Gson().toJson( envs ) );
	}

}
